var React = require('react');

var EditPost = React.createClass({
  getInitialState: function () {
    return {
      id: $.getQuery('id'),
      title: "",
      content: "",
      typeList: [],
      type: -1
    };
  },

  componentDidMount: function () {
    $.getJSON(baseUrl + "getTextTypeList", function (result, status) {

      if (this.isMounted()) {
        this.setState({
          typeList: result.data
        });
      }
    }.bind(this)).fail(function () {
      location.href = 'index.html';
    });

    $.getJSON(baseUrl + "getTextAndCommentByTextId/" + this.state.id, function (result, status) {
      if (this.isMounted()) {
        this.setState({
          title: result.data[0].title,
          content: result.data[0].text,
          type: result.data[0].text_type.id
        });
      }

    }.bind(this));
  },

  handleEditPost: function () {
    if ($.isBlank($('#edit-post-title').val()) || $.isBlank($('#edit-post-content').val()) || $.isBlank($('#type-select').val())) {
      console.log("empty, return");
      return;
    }

    var data = {
      title: $('#edit-post-title').val(),
      text: $('#edit-post-content').val(),
      text_type: parseInt($('#type-select').val())
    };

    console.log(data);
    $.post(baseUrl + "updateText/" + this.state.id, data, function (result, status) {
      var post = result.data[0];
      location.href = 'post.html?id=' + post.id;
    }, 'json');
  },

  handleTitleChange: function (event) {
    this.setState({
      title: event.target.value
    });
  },
  handleContentChange: function (event) {
    this.setState({
      content: event.target.value
    });
  },

  render: function () {
    return (
      <div>
        <div className="devide-title">
          <h1>编辑文章</h1>
        </div>
        <div className="edit-post">
          <input id="edit-post-title" onChange={this.handleTitleChange} placeholder="标题" type="text" value={this.state.title}/>
          <select id="type-select">
            {this.state.typeList.map(function (e) {
          var selectState = "";
          if (e.id == this.state.type) {
            selectState = "selected";
          }
          return (
              <option key={e.id} selected={selectState} value={e.id}>
                {e.name}
              </option>
          )
        }, this)}
          </select>
          <br/>
          <textarea id="edit-post-content" onChange={this.handleContentChange} placeholder="文章内容" value={this.state.content}></textarea>
          <br/>
          <input id="edit-post-button" onClick={this.handleEditPost} type="button" value="更新"/>
        </div>
      </div>
    );
  }
});

module.exports = EditPost;
